<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body>div {
            width: 200px;
            height: 200px;
            background-color: skyblue;
        }
    </style>
</head>

<body>
    <div></div>
</body>
<script>
    /*      在页面中摆放一个div盒子，宽高200px，
    当我们按下 a(左)s（下）d（右）w（上）方向键的时候，让盒子按照对应方向进行移动
    
    要求盒子不能超出当前页面可见区域 */

    // 获取元素
    const div = document.querySelector('div');

    // 注册事件
    document.addEventListener('keydown', function (e) {
        // a:65 s:83 d:68 w:87
        // 合法距离
        let diffX = window.innerWidth - 200;
        let diffY = window.innerHeight - 200;
        // 分配步长
        let stepX = diffX / 10;
        let stepY = diffY / 10;
        // 盒子边距
        let top = div.offsetTop;
        let left = div.offsetLeft;

        // 左移动
        if (e.keyCode == 65) {
            left -= stepX;
            if (left < 0) left = 0;
            div.style.marginLeft = `${left}px`;
        }

        // 下移动
        if (e.keyCode == 83) {
            top += stepY;
            if (top > diffY) top = diffY;
            div.style.marginTop = `${top}px`;
        }

        // 右移动
        if (e.keyCode == 68) {
            left += stepX;
            if (left > diffX) left = diffX;
            div.style.marginLeft = `${left}px`;
        }

        // 上移动
        if (e.keyCode == 87) {
            top -= stepY;
            if (top < 0) top = 0;
            div.style.marginTop = `${top}px`;
        }
    });
</script>

</html>